# Filters added to this controller apply to all controllers in the application.
# Likewise, all the methods added will be available for all controllers.

require 'gettext'
require 'gettext_activerecord'
require 'gettext_rails'

class ApplicationController < ActionController::Base
  init_gettext "mbds_dynamic"
  init_gettext "mbds"
  
  include AuthenticatedSystem
  
  helper :all
  protect_from_forgery
  filter_parameter_logging :password
  
  before_filter :login_from_cookie
  before_filter :define_tabs
  before_filter :set_locale
  
  after_filter :http_expiration
    rescue_from Exception, :with => :render_error

  def render_error(exception)
    logger.info "User logged : #{current_user.inspect}"
    log_error(exception)
    render :template => "/errors/error.html.erb"
  end

  def define_tabs
    @tabs = []
    if logged_in? and current_user.is_admin
      @tabs.push [:reports, _('Implementation Report'), url_for(:controller => 'reports', :action => 'index')]
      @tabs.push [:users, _('Authorized User List'), url_for(:controller => 'users', :action => 'index')]
      @tabs.push [:map, _('Map'), url_for(:controller => 'users', :action => 'map')]
      @tabs.push [:language, _('Translations'), url_for(:controller => 'users', :action => 'admin_lang')]
    elsif logged_in? and (current_user.is_admin or not(current_user.is_only_xb?))
      @tabs.push [:reports, _('Implementation Report'), url_for(:controller => 'reports', :action => 'index')]
      @tabs.push [:users, _('Authorized User List'), url_for(:controller => 'users', :action => 'index')]
      @tabs.push [:map, _('Map'), url_for(:controller => 'users', :action => 'map')]
    end
    true
  end
  
  def set_locale
    # if params[:locale] is nil then I18n.default_locale will be used
    if logged_in? 
      GetText.locale = current_user.preferred_language
    end
  end
  
  def admin_only
    if logged_in? and current_user.is_admin
         true
      else
         render :nothing => true, :status => 401 
         false
      end
  end
  
  def http_expiration
    # Fixed old date to ensure content always expires
    headers['Expires'] = "Sat, 01 Jan 2000 00:00:00 GMT"
  end
  
end

